package com.lovi.thread_;

/**
 * 演示线程的TimedWaiting、Blocked和Waiting状态。
 */
public class ThreadStatesExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个共享的对象锁
        final Object lock = new Object();

        // 创建一个线程用于演示Waiting状态
        Thread waitingThread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("waitingThread is going to wait.");
                    lock.wait(); // 进入Waiting状态
                    System.out.println("waitingThread has been notified and resumed.");
                } catch (InterruptedException e) {
                    System.out.println("waitingThread was interrupted while waiting.");
                }
            }
        });

        // 创建一个线程用于演示TimedWaiting状态
        Thread timedWaitingThread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("timedWaitingThread is going to sleep for 5 seconds.");
                    Thread.sleep(5000); // 进入TimedWaiting状态
                    System.out.println("timedWaitingThread has woken up after sleeping.");
                } catch (InterruptedException e) {
                    System.out.println("timedWaitingThread was interrupted while sleeping.");
                }
            }
        });

        // 创建一个线程用于演示Blocked状态
        Thread blockedThread = new Thread(() -> {
            synchronized (lock) {
                System.out.println("blockedThread has acquired the lock and will hold it for 5 seconds.");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    System.out.println("blockedThread was interrupted while holding the lock.");
                }
                System.out.println("blockedThread has released the lock.");
            }
        });

        // 启动所有线程
        waitingThread.start();
        timedWaitingThread.start();
        blockedThread.start();

        // 让主线程等待一段时间，确保所有子线程都已经启动
        Thread.sleep(1000);

        // 唤醒waitingThread
        synchronized (lock) {
            lock.notify();
        }

        // 主线程等待所有子线程完成
        waitingThread.join();
        timedWaitingThread.join();
        blockedThread.join();

        System.out.println("All threads have completed execution.");
    }
}




